<template>
    <div class="app-container">
        <el-form
            class="filters"
            ref="searchForm"
            size="mini"
            :model="searchForm"
            label-width="90px"
        >
            <el-row>
                <el-col :span="5">
                    <el-form-item label="设备编码" style="width: 100%">
                        <el-input
                            type="textarea"
                            :rows="3"
                            :placeholder="'请输入柜号，多个编码之间请回车换行，禁止输入特殊字符！输入示例：\nCC08DPC0202204250001\nCC08DPC0202205070001\n0000092011500063'"
                            v-model="searchForm.codes"
                            @change.native="keyUp($event)"
                            @input.native="keyInput($event)"
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="19" class="filters">
                    <el-form-item label="厂商" v-if="platformType == 'P'">
                        <el-select
                            clearable
                            v-model="searchForm.organizationId"
                            placeholder="请选择厂商"
                            @change="organizeChange"
                        >
                            <el-option
                                v-for="item in factuerOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="运营商">
                        <el-select
                            clearable
                            :disabled="!searchForm.organizationId"
                            v-model="searchForm.operatorId"
                            placeholder="请先选择厂商"
                        >
                            <el-option
                                v-for="item in operatorOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备型号">
                        <el-select
                            clearable
                            v-model="searchForm.equipModeIds"
                            multiple
                            placeholder="请选择设备型号"
                        >
                            <el-option
                                v-for="item in modelOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="联网状态">
                        <el-select
                            clearable
                            v-model="searchForm.isOnline"
                            placeholder="请选择联网状态"
                        >
                            <el-option
                                v-for="item in enumsJson.IS_ONLINE"
                                :key="item.code"
                                :label="item.label"
                                :value="item.code"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务状态">
                        <el-select
                            v-model="searchForm.status"
                            clearable
                            placeholder="请选择业务状态"
                        >
                            <el-option
                                v-for="item in enumsJson.EQUIP_STATUS"
                                :key="item.code"
                                :label="item.label"
                                :value="item.code"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="标签">
                        <el-select
                            v-model="searchForm.tagIds"
                            multiple
                            collapse-tags
                            placeholder="请选择标签"
                            clearable
                        >
                            <el-option
                                v-for="item in tagsOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="告警内容">
                        <el-input
                            clearable
                            v-model="searchForm.name"
                            placeholder="请输入告警内容"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="地区" class="area-select">
                        <el-cascader
                            clearable
                            :options="areaSelectData"
                            :props="areaSelectDataProps"
                            ref="areaSelectRef"
                            size="large"
                            v-model="searchForm.regionCode"
                            placeholder="请选择省市区"
                        />
                    </el-form-item>
                    <el-form-item label="详细地址">
                        <el-input
                            clearable
                            v-model="searchForm.address"
                            placeholder="请输入详细地址"
                        />
                    </el-form-item>
                    <div class="search-btns">
                        <el-button
                            type="primary"
                            size="mini"
                            icon="el-icon-search"
                            @click="doSearch"
                            >搜索</el-button
                        >
                        <el-button
                            type="default"
                            size="mini"
                            icon="el-icon-refresh"
                            @click="resetSearch"
                            >重置</el-button
                        >
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <el-table
            class="listTable"
            style="width: 100%"
            :header-cell-style="{
                padding: '2.5px 0',
                background: '#ECF1F7',
                textAlign: 'center',
            }"
            :data="tableData"
            row-key="id"
            border
            v-loading="listLoading"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
            <el-table-column
                label="序号"
                width="50"
                fix="true"
                type=""
                align="center"
            >
                <template slot-scope="scope" v-if="scope.row.indexs">
                    {{ scope.row.indexs }}
                </template>
            </el-table-column>
            <el-table-column
                label="设备编码"
                type=""
                align="center"
                width="240"
            >
                <template slot-scope="scope">
                    <div class="codes">
                        <span>{{ scope.row.code }}</span>
                        <DetectOnline
                            :currentRow="scope.row"
                            @updateStatus="fetchData"
                        ></DetectOnline>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                prop="name"
                label="告警内容"
                align="left"
                class-name="warnCloumn"
                min-width="180"
            >
            </el-table-column>
            <el-table-column
                prop="addrId"
                label="地址Id"
                align="center"
                width="65"
            >
            </el-table-column>
            <el-table-column prop="value" label="值" align="center">
            </el-table-column>
            <el-table-column
                prop="occurrenceTime"
                label="上报时间"
                align="center"
                width="180"
            >
            </el-table-column>
            
            <el-table-column label="标签">
                <template slot-scope="scope">
                <div class="tags-content" v-if="scope.row.id && scope.row.code">
                    <Tags  :closable="true" closePermission="om:currentalarm:deleteTag"
                        :currentRow="scope.row"
                        @updateList="fetchData"
                    ></Tags>
                    <i class="el-icon-circle-plus-outline" @click="tagSetShow(scope.row)" v-permission="['om:currentalarm:insertTag']"></i>
                </div>
            </template>
        </el-table-column>
            <el-table-column label="操作" width="520" align="center">
                <!-- 换电柜：柜详情、参数设置、仓控制、重启 -->
                <!-- 充电堆：系统详情、参数设置、端口、重启 -->
                <template slot-scope="scope" v-if="scope.row.code">
                    <!--换电柜 -->
                    <el-button
                        type="primary"
                        size="mini"
                        v-permission="['om:currentalarm:cabinetDetails']"
                        :disabled="!scope.row.isAllowOperate"
                        @click="boxDialog(scope.row)"
                        >柜详情</el-button
                    >
                    <el-button
                        class="fifth-btn"
                        type="primary"
                        size="mini"
                        :disabled="!scope.row.isAllowOperate"
                        v-permission="['om:currentalarm:camera']"
                        @click="cameraDialog(scope.row)"
                        >摄像头</el-button
                    >
                    <el-button
                        class="third-btn"
                        type="primary"
                        size="mini"
                        :disabled="!scope.row.isAllowOperate"
                        @click="boxStatusDialog(scope.row)"
                        v-permission="['om:currentalarm:statusEvaluation']"
                        >柜状态评估</el-button
                    >
                    <el-button
                        type="success"
                        size="mini"
                        :disabled="!scope.row.isAllowOperate"
                        @click="isEditDialog(scope.row)"
                        v-permission="['om:currentalarm:parameter']"
                        >参数设置</el-button
                    >

                    <el-button
                        type="warning"
                        size="mini"
                        :disabled="!scope.row.isAllowOperate"
                        @click="binDialog(scope.row)"
                        v-permission="['om:currentalarm:control']"
                        >仓控制</el-button
                    >
                    <el-button
                        type="danger"
                        size="mini"
                        @click="isReStart(scope.row)"
                        :disabled="!scope.row.isAllowOperate"
                        v-permission="['om:currentalarm:restart']"
                        >重启</el-button
                    >

                    <!--充电堆 -->
                    <el-button
                        type="primary"
                        size="mini"
                        v-permission="['om:currentalarm:systemDetails']"
                        :disabled="!scope.row.isAllowOperate"
                        @click="systemDialog(scope.row)"
                        >系统详情</el-button
                    >

                    <el-button
                        type="warning"
                        v-permission="['om:currentalarm:port']"
                        size="mini"
                        :disabled="!scope.row.isAllowOperate"
                        @click="portDialog(scope.row)"
                        >端口</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />

        <!-- 参数设置弹框 -->
        <Dialog
            :visible="visible"
            width="60%"
            :isFooter="false"
            :title="dialogTitle"
            @cancelDialog="cancelDialog"
        >
            <Params
                class="box-detail"
                :equipId="equipId"
                @cancelDialog="cancelDialog"
                :visible="visible"
            ></Params>
        </Dialog>
        <!-- 仓控制 -->
        <Dialog
            :visible="binVisible"
            width="50%"
            :isFooter="false"
            :title="dialogTitle"
            @cancelDialog="binDetailClose"
        >
            <binDetail
                :equipId="equipId"
                :binVisible="binVisible"
                @changeForbidList="changeForbidList"
                @showProgress="showProgress"
                @changeProgressList="changeProgressList"
            ></binDetail>
        </Dialog>
        <!-- 柜详情 -->
        <Dialog
            :visible="boxVisible"
            width="68%"
            :isFooter="false"
            :title="dialogTitle"
            @confirmDialog="confirmDialog"
            @cancelDialog="boxVisible = false"
        >
            <boxDetail
                class="box-detail"
                :currentRow="currentRow"
                :boxVisible="boxVisible"
            ></boxDetail>
        </Dialog>
        <!-- 柜详情进度 -->
        <el-dialog
            title="仓控制"
            :visible.sync="boxProgressVisible"
            width="25%"
            :show-close="false"
            class="binControlContent"
        >
            <boxProcess
                :progressList="progressList"
                :forbidList="forbidList"
                @handleCloseProcess="handleCloseProcess"
            ></boxProcess>
        </el-dialog>
        <!-- 重启设置 -->
        <Dialog
            :visible="restartVisible"
            width="25%"
            :isFooter="false"
            :title="dialogTitle"
            @cancelDialog="cancelStartDialog"
        >
            <restartSet
                :restartVisible="restartVisible"
                :currentRow="currentRow"
                @cancelStartDialog="cancelStartDialog"
            ></restartSet>
        </Dialog>

        <!-- 充电堆操作项 -->
        <!-- 系统详情 -->
        <Dialog
            :visible="CSystemVisible"
            width="55%"
            :isFooter="false"
            :title="CSystemTitle"
            @cancelDialog="ECSystemCancelDialog"
        >
            <SystemDetail
                class="table-box"
                :currentRow="currentRow"
                :CSystemVisible="CSystemVisible"
            ></SystemDetail>
        </Dialog>
        <!-- 参数详情 -->
        <Dialog
            :visible="CSParamVisible"
            width="42%"
            :isFooter="false"
            :title="CSParamTitle"
            @confirmDialog="CSParamConfirmDialog"
            @cancelDialog="CSParamCancelDialog"
        >
            <CSParams
                :currentRow="currentRow"
                :CSParamVisible="CSParamVisible"
            ></CSParams>
        </Dialog>

        <!-- 端口 -->
        <Dialog
            :visible="portVisible"
            width="45%"
            :isFooter="false"
            :title="portTitle"
            @confirmDialog="portConfirmDialog"
            @cancelDialog="portCancelDialog"
        >
            <Port :currentRow="currentRow" :portVisible="portVisible"></Port>
        </Dialog>

        <!-- 摄像头 -->
        <Dialog
            :visible="cameraVisible"
            width="35%"
            :isFooter="false"
            :title="dialogTitle"
            @cancelDialog="cameraVisible = false"
        >
            <cameraDetail
                :currentRow="currentRow"
                :equipId="equipId"
                :cameraVisible="cameraVisible"
            ></cameraDetail>
        </Dialog>
        <!-- 柜状态评估 -->
        <Dialog
            :visible="boxStatusVisible"
            width="35%"
            :isFooter="false"
            :title="dialogTitle"
            @cancelDialog="boxStatusVisible = false"
        >
            <boxStatus
                :currentRow="currentRow"
                :equipId="equipId"
                :boxStatusVisible="boxStatusVisible"
            ></boxStatus>
        </Dialog>

        <!-- 单个设备标签编辑 -->
        <Dialog
            :visible="tagSetVisible"
            width="30%"
            title="设置标签"
            @cancelDialog="tagSetVisible = false"
            @confirmDialog="tagSetConfirmDialog"
        >
        <TagSet :currentRow="currentRow" :tagSetVisible="tagSetVisible" @handleTagSetChange="handleTagSetChange"></TagSet>
        </Dialog>
    </div>
</template>

<script>
import { alarms } from "@/api/manage";
import { operator } from "@/api/factuer";

import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
import Params from "./params";
import boxDetail from "./boxDetail";
import cameraDetail from "./cameraDetail.vue";
import { removeNullUndefined } from "@/utils/index.js";

import { mapGetters } from "vuex";

import operatejs from "./CS/operate.js";
import SystemDetail from "./CS/systemDetail.vue";
import CSParams from "./CS/param.vue";
import Port from "./CS/port.vue";

import restartSet from "./restartSet.vue";
import binDetail from "./binDetail.vue";
import boxProcess from "./boxProcess.vue";
import boxStatus from "./boxStatus.vue";

import DetectOnline from "@/views/equipment/equipentry/components/detectOnline.vue";
import Tags from "@/views/equipment/equipentry/components/tags.vue";
import TagSet from "@/views/equipment/equipentry/components/tagSet.vue";
import tagsjs from "@/views/equipment/equipentry/js/operate";

export default {
    components: {
        Pagination,
        Table,
        Dialog,
        Params,
        boxDetail,
        SystemDetail,
        CSParams,
        Port,
        cameraDetail,
        restartSet,
        binDetail,
        boxProcess,
        boxStatus,
        DetectOnline,

        Tags,
        TagSet,
    },
    mixins: [operatejs,tagsjs],

    data() {
        return {
            listLoading: true,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                name: "", //告警内容
                codes: "",
                organizationId: "",
                equipModeIds: [],
                operatorId: "",
                status: "",
                isOnline: "",
                regionCode: "",
                address: "",
                tagIds:[],
            },

            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                { slot: "codes", label: "设备编码", width: "300" },
                {
                    label: "告警内容",
                    prop: "name",
                    width: "80",
                },
                {
                    label: "地址Id",
                    prop: "addrId",
                    width: "30",
                },
                {
                    label: "上报时间",
                    prop: "occurrenceTime",
                    width: "40",
                },
                { slot: "tags", label: "标签" },
                { slot: "action", label: "操作" },
            ],
            tableData: [],
            visible: false, //弹框标识
            boxVisible: false,
            dialogForm: {
                name: "",
                code: "",
            },

            dialogTitle: "",

            areaSelectData: [], // options绑定的数据就是引入的 provinceAndCityData
            areaSelectDataProps: {
                // multiple: true,
                // checkStrictly: true,
                // multipleLimit: 3,
                children: "childrens",
                value: "code",
                label: "name",
                emitPath: false,
            },
            operatorOption: [], //运营商option
            factuerOption: [], //厂商option
            enumsJson: {},
            modelOption: [], //设备型号option
            equipId: "", //设备id
            currentRow: {}, //当前行
            restartVisible: false,

            binVisible: false,

            boxProgressVisible: false,
            progressList: [],
            forbidList: [],
            binSwitch: false,
            platformType: this.$store.state.user.platformType,
            organizationId: this.$store.state.user.organizationId,

            // CS
            CSystemVisible: false,
            CSystemTitle: "",

            CSParamVisible: false,
            CSParamTitle: "",

            portVisible: false,
            portTitle: "",

            cameraVisible: false,
            boxStatusVisible: false,

            tagsOption: [],
        };
    },
    computed: {
        ...mapGetters(["enums", "equipTypeCode"]),
    },

    watch: {
        enums: {
            async handler(cur, old) {
                if (!old && Object.keys(cur).length == 0) {
                    this.enumsJson = await this.$store.dispatch(
                        "enums/generateEnumMap"
                    );
                } else {
                    this.enumsJson = this.$store.state.enums.enums;
                }
            },
            deep: true, //对象内部的属性监听，也叫深度监听
            immediate: true,
        },
    },
    async created() {
        if (this.platformType != "P") {
            //非平台用户
            this.searchForm.organizationId = this.organizationId;
            this.organizeChange(this.organizationId);
        } else {
            this.factuerOption = await this.$store.dispatch(
                "operator/generatorFactuer"
            );
        }
        this.fetchData();
        this.getOperator();
    },
    methods: {
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            let param = { ...this.searchForm };

            if (param.codes) {
                param.codes = param.codes.split("\n").filter((item) => item);
            }
            if (param.codes.length == 1) {
                param.code = param.codes[0];
                delete param.codes;
            }
            alarms(
                "/existing/list",
                "post",
                {
                    ...removeNullUndefined(param),
                },
                1
            )
                .then((res) => {
                    let datas = res.data;
                    this.total = +res.total;

                    datas.forEach((item, index) => {
                        item.indexs = index + 1;
                        if (item.alarms.length > 0) {
                            item.name = item.alarms[0].name;
                            item.occurrenceTime = item.alarms[0].occurrenceTime;
                            item.addrId = item.alarms[0].addrId;
                            item.value = item.alarms[0].value;
                        }
                        item.alarms.forEach((pp, inx) => {
                            pp.id = `alarm-${index} - ${inx}`;
                        });
                        item.children = item.alarms.filter(
                            (t, index) => index > 0
                        );
                    });
                    this.tableData = datas;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },
        async getOperator() {
            this.areaSelectData = await this.$store.dispatch(
                "operator/generatorRegion"
            );
            this.modelOption = await this.$store.dispatch(
                "operator/generatorModel"
            );
            this.tagsOption = await this.$store.dispatch(
                "operator/generatorTags"
            );
        },
        async organizeChange(e) {
            this.operatorOption = [];
            this.searchForm.operatorId = "";
            if (e) {
                let datas = await operator("/all", "get", {
                    organizationId: e,
                });
                this.operatorOption = datas.data;
            }
        },

        // 弹框取消
        cancelDialog() {
            this.visible = false;
        },
        // 弹框确认
        confirmDialog() {
            this.submitDialogForm("dialogForm");
        },

        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert("submit!");
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetDialogForm(formName) {
            this.$refs[formName].resetFields();
        },

        //限制输入特殊字符
        keyUp(e) {
            let str = e.target.value.replace(
                /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                ""
            );
            e.target.value = str;
            this.searchForm.codes = str;
        },
        // 只能输入汉字、英文、数字
        keyInput(e) {
            let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
            e.target.value = str;
            this.searchForm.codes = str;
        },
        resetSearch() {
            this.searchForm = {
                pageNum: this.searchForm.pageNum,
                pageSize: this.searchForm.pageSize,
                name: "", //告警内容
                codes: "",
                organizationId:
                    this.platformType != "P" ? this.organizationId : null,
                equipModeIds: [],
                operatorId: "",
                status: "",
                isOnline: "",
                regionCode: "",
                address: "",
                tagIds:[],
            };
        },

        cancelStartDialog() {
            this.restartVisible = false;
        },

        showProgress() {
            this.boxProgressVisible = true;
        },
        changeForbidList(e) {
            this.forbidList = e;
        },
        changeProgressList(e) {
            this.progressList = e;
        },
        handleCloseProcess() {
            this.boxProgressVisible = false;
            this.progressList = [];
            this.forbidList = [];
        },
        doSearch() {
            this.searchForm.pageNum = 1;
            this.fetchData();
        },
        binDetailClose() {
            this.binVisible = false;
        },
    },
};
</script>

<style scoped lang="scss">
@import "@/styles/common.scss";
@import "./css/style.scss";
.binControlContent {
    ::v-deep .el-dialog__body {
        padding: 0 10px 10px;
        text-align: center;
    }
}
.tags-content {
    @include flexLayout(center, center);
    .el-icon-circle-plus-outline {
        cursor: pointer;
        position: relative;
        right: -8px;
        color: #5473e8;
        font-size: 16px;
    }
}
::v-deep .el-select__tags{
    .el-tag:first-child{
        max-width: 72%;
    }
}
</style>
